package com.yeswater.es.test;

import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.*;
import org.elasticsearch.cluster.metadata.AliasMetadata;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * author： yeswater
 * create： 2024/4/2
 */
public class ESTest_Index {
    public static void main(String[] args) throws IOException {
        RestHighLevelClient esClient = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", Integer.parseInt("9200"), "http")));
        
        createIndex(esClient, "user");
        System.out.println("=== ===");
        getIndex(esClient, "user");
        System.out.println("=== ===");
        deleteIndex(esClient, "user");
        System.out.println("=== ===");
        getIndex(esClient, "user");
        esClient.close();
    }
    
    /**
     * 创建索引
     */
    private static void createIndex(RestHighLevelClient esClient, String index) {
        CreateIndexRequest req = new CreateIndexRequest("user");
        CreateIndexResponse resp = null;
        try {
            resp = esClient.indices().create(req, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 响应状态
        boolean acknowledged = resp.isAcknowledged();
        System.out.println("创建索引 : " + acknowledged);
    }
    
    /**
     * 查询索引
     */
    private static void getIndex(RestHighLevelClient esClient, String index) {
        GetIndexRequest req = new GetIndexRequest(index);
        GetIndexResponse resp = null;
        try {
            resp = esClient.indices().get(req, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        System.out.println(resp.getAliases());
        System.out.println(resp.getMappings());
        System.out.println(resp.getSettings());
    }
    
    /**
     * 删除索引
     */
    private static void deleteIndex(RestHighLevelClient esClient, String index) {
        DeleteIndexRequest req = new DeleteIndexRequest("user");
        AcknowledgedResponse resp = null;
        try {
            resp = esClient.indices().delete(req, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        System.out.println("delete : " + resp.isAcknowledged());
    }
}
